package com.jiuyuejiu.func_video.video.fenlei;

import android.content.Intent;
import android.graphics.Color;
import android.hardware.Sensor;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.AbsListView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.Toast;

import com.jiuyuejiu.R;
import com.jiuyuejiu.application.ConstValues;
import com.jiuyuejiu.base.BaseActivity;
import com.jiuyuejiu.func_video.adapter.VideoListAdapter;
import com.jiuyuejiu.func_video.VideoService;
import com.jiuyuejiu.func_video.domain.VideoDetailStc;
import com.jiuyuejiu.func_video.domain.VideoFenleiStc;
import com.jiuyuejiu.utils.ShanHaiUtil;
import com.jiuyuejiu.utils.ViewUtil;
import com.kylin.core.utils.dbtutil.FunUtil;
import com.kylin.core.utils.flyn.Eyes;

import java.io.File;
import java.lang.ref.SoftReference;
import java.util.ArrayList;

import androidx.annotation.Nullable;
import androidx.appcompat.widget.AppCompatTextView;
import cn.jzvd.Jzvd;

/**
 * 每个分类的视频列表
 */
public class VideoListActivity extends BaseActivity implements View.OnClickListener {

    private RelativeLayout backBtn;
    private RelativeLayout confirmBtn;
    private AppCompatTextView confirmTv;
    private AppCompatTextView backTv;
    private AppCompatTextView titleTv;

    ListView listView;

    SensorManager sensorManager;
    Jzvd.JZAutoFullscreenListener sensorEventListener;


    private VideoService service;
    private MyHandler handler;

    // 是否当前页面 第一次发起请求
    private String fileName;

    // 上一页传递过来的名称
    private VideoFenleiStc stc;


    /**
     * 接收子线程消息的 Handler
     */
    public static class MyHandler extends Handler {

        // 软引用
        SoftReference<VideoListActivity> fragmentRef;

        public MyHandler(VideoListActivity fragment) {
            fragmentRef = new SoftReference<VideoListActivity>(fragment);
        }

        @Override
        public void handleMessage(Message msg) {
            VideoListActivity fragment = fragmentRef.get();
            if (fragment == null) {
                return;
            }
            Bundle bundle = msg.getData();

            // 处理UI 变化
            switch (msg.what) {
                case ConstValues.WAIT0: // 下载文件的回调
                    fragment.getJsonSuc(bundle);
                    break;
            }
        }
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_video_vlistview);

        // 标题栏白底黑字
        Eyes.setStatusBarLightMode(this, Color.WHITE);

        // 初始化视图
        initView();
        // 初始化数据
        initData();

    }

    // 初始化视图
    private void initView() {

        backBtn = (RelativeLayout) findViewById(R.id.top_navigation_rl_back);
        confirmBtn = (RelativeLayout) findViewById(R.id.top_navigation_rl_confirm);
        confirmTv = (AppCompatTextView) findViewById(R.id.top_navigation_bt_confirm);
        backTv = (AppCompatTextView) findViewById(R.id.top_navigation_bt_back);
        titleTv = (AppCompatTextView) findViewById(R.id.top_navigation_tv_title);
        backBtn.setVisibility(View.VISIBLE);
        confirmBtn.setVisibility(View.INVISIBLE);
        backBtn.setOnClickListener(this);
        confirmBtn.setOnClickListener(this);

        listView = findViewById(R.id.listview);
    }

    // 初始化数据
    private void initData() {
        handler = new MyHandler(VideoListActivity.this);
        service = new VideoService(VideoListActivity.this, handler);

        // 获取上一页传递过来的数据
        Intent i = getIntent();
        stc = (VideoFenleiStc) i.getSerializableExtra("VideoFenleiStc");

        titleTv.setText(stc.getCategory());

        sensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
        sensorEventListener = new Jzvd.JZAutoFullscreenListener();

        //
        fileName = FunUtil.StringToMd5(stc.getCategory());

        if (hasPermission(ConstValues.WRITE_READ_EXTERNAL_PERMISSION)) {
            // 拥有了此权限,那么直接执行业务逻辑

            // 读取本地txt
            readTxtFromPhone();

        } else {
            // 还没有对一个权限(请求码,权限数组)这两个参数都事先定义好
            requestPermission(ConstValues.WRITE_READ_EXTERNAL_CODE, ConstValues.WRITE_READ_EXTERNAL_PERMISSION);
        }
    }

    // 读取本地txt
    private void readTxtFromPhone() {


        // 拼接文件路径
        String pdfpath = ShanHaiUtil.parseFilePath(fileName);
        File docFile = new File(pdfpath);
        if (docFile.exists()) {//存在本地;
            try {
                // 传入File文件 读取文件内容
                String result = ShanHaiUtil.parseFileToString(docFile);
                // 传入字符串 将字符串分割成数组
                String[] read = ShanHaiUtil.splitStringToArray(result);
                // 将数组 转成 集合
                final ArrayList<VideoDetailStc> videoDetailStcs = ShanHaiUtil.getVideoListByVideoArray(stc.getCategory(),
                        ConstValues.LANDKING + "/" + ConstValues.VIDEONAME + "/", read);

                try {
                    //
                    if (videoDetailStcs != null && videoDetailStcs.size() > 0) {

                        VideoListAdapter adapter = new VideoListAdapter(this, stc, videoDetailStcs);
                        listView.setAdapter(adapter);
                        listView.setOnScrollListener(new AbsListView.OnScrollListener() {
                            @Override
                            public void onScrollStateChanged(AbsListView view, int scrollState) {

                            }

                            @Override
                            public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
                                if (Jzvd.CURRENT_JZVD == null)
                                    return;
                                int lastVisibleItem = firstVisibleItem + visibleItemCount;
                                int currentPlayPosition = Jzvd.CURRENT_JZVD.positionInList;
                                //                Log.e(TAG, "onScrollReleaseAllVideos: " +
                                //                        currentPlayPosition + " " + firstVisibleItem + " " + currentPlayPosition + " " + lastVisibleItem);
                                if (currentPlayPosition >= 0) {
                                    if ((currentPlayPosition < firstVisibleItem || currentPlayPosition > (lastVisibleItem - 1))) {
                                        if (Jzvd.CURRENT_JZVD.screen != Jzvd.SCREEN_FULLSCREEN) {
                                            Jzvd.releaseAllVideos();//为什么最后一个视频横屏会调用这个，其他地方不会
                                        }
                                    }
                                }
                            }
                        });
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    Toast.makeText(VideoListActivity.this, "没有找到指定文件", Toast.LENGTH_SHORT).show();
                }

            } catch (Exception e) {
                e.printStackTrace();
                Toast.makeText(VideoListActivity.this, "没有找到指定文件", Toast.LENGTH_SHORT).show();
            }
        } else {// 本地不存在
            // 下载文件
            downloadFile();
        }
    }

    private void downloadFile() {
        String serviceip = ShanHaiUtil.getHttpid();
        String downurl = serviceip + ConstValues.LANDKING + "/" + ConstValues.VIDEONAME + "/" + stc.getCategory() + "/" + ConstValues.TXTNAME;

        // 下载文件到本地
        service.downCatVideoJsonList(downurl,// 请求url
                fileName, // 本地存储名称
                false, // 是否显示进度条 false不显示下载进度,true显示下载进度框
                ConstValues.WAIT0);// 用于当前Activity界面handle的对应回调接收 比如what1,what2
    }

    // 手动拥有读写权限后 执行下载文件
    @Override
    public void doWriteSDCard() {
        try {
            // 拥有了此权限,那么直接执行业务逻辑
            // 读取本地txt
            readTxtFromPhone();

        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    private void getJsonSuc(Bundle bundle) {

        String formjson = bundle.getString("formjson");
        String status = bundle.getString("status");

        if (ConstValues.SUCCESS.equals(status)) {
            // 读取本地txt
            readTxtFromPhone();
        } else {
            Toast.makeText(VideoListActivity.this, formjson, Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.top_navigation_rl_back://
                if (ViewUtil.isDoubleClick(v.getId(), 2500))
                    return;
                this.finish();
                break;
        }
    }

    @Override
    public void onBackPressedSupport() {
        if (Jzvd.backPress()) {
            return;
        }
        super.onBackPressedSupport();
    }

    @Override
    protected void onResume() {
        super.onResume();
        Sensor accelerometerSensor = sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
        sensorManager.registerListener(sensorEventListener, accelerometerSensor, SensorManager.SENSOR_DELAY_NORMAL);
    }

    @Override
    protected void onPause() {
        super.onPause();
        sensorManager.unregisterListener(sensorEventListener);
        Jzvd.releaseAllVideos();
    }


}
